package com.zzq.my.jetpacks.jectpackapp.kt

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Base64
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream

@Desc("Bitmap转File", "v1.0.1")
fun Bitmap.saveFile(
    path: String,
    format: Bitmap.CompressFormat = Bitmap.CompressFormat.PNG,
    quality: Int = 100
) {
    try {
        val file = File(path)
        val out = FileOutputStream(file)
        this.compress(format, quality, out)
        out.flush()
        out.close()
    } catch (e: Exception) {
        e.printStackTrace()
    }

}


//todo file 转 bitmap
fun File.getBitmap(): Bitmap {
    return BitmapFactory.decodeFile(this.absolutePath)
}

@Desc("Bitmap装base64", "v1.0.1")
fun Bitmap.base64(
    quality: Int = 100,
    format: Bitmap.CompressFormat = Bitmap.CompressFormat.PNG
): String {
    val bos = ByteArrayOutputStream()
    this.compress(format, quality, bos)
    val bytes = bos.toByteArray()

    val encode = Base64.encode(bytes, Base64.DEFAULT)
    return String(encode)
}

/**
 * bitmap 缩放
 */
fun Bitmap.scale(newWidth: Int, newHeight: Int, recycle: Boolean = false): Bitmap {
    var ret = Bitmap.createScaledBitmap(this, newWidth, newHeight, true)
    if (recycle && !this.isRecycled) this.recycle()
    return ret
}